﻿# -*- coding:utf-8 -*-

#from sklad.views.categories import create_category_tree_ex
from django.core.urlresolvers import reverse
from sklad.models import Category

def recursive_get_category_list_ex(cat, level, expanded_catid):
    res = []
    for ci in cat:
        item = {"id":ci.id,"name":ci.name,"parent":ci.parent,"level":level,"csslevel":level*12,"expanded":False,}
        if expanded_catid:
            if item["id"] in expanded_catid:
                item["expanded"]=True    
        else:
            item["expanded"]=True
        category_set = ci.category_set.all()
        item["child_present"] = category_set
        res.append(item)
        if(item["expanded"]): 
            subcategories=recursive_get_category_list_ex(category_set, level+1, expanded_catid)
            res.extend(subcategories)
    return res



def create_category_tree_ex(expanded_catid):
    c = Category.objects.select_related().filter(parent=None)
    return recursive_get_category_list_ex(c, 0, expanded_catid)


def get_category_path(category_id):
    if category_id == None:
        return None
    path = []
    category = Category.objects.select_related().get(id=category_id)
    while category != None:
        path.insert(0,category)
        category = category.parent
    return path


def category_proc(request):
    "A context processor that provides cattree & excat."

    if "current_category" not in request.session:
        request.session["current_category"] = None

    if "expanded_catid" not in request.session:
        request.session["expanded_catid"] = [0]
    cattree = create_category_tree_ex(request.session["expanded_catid"])
    curcat = request.session["current_category"]

    gm = ""
    if "global_message" in request.session:
        gm = request.session["global_message"]

    return {
        'cattree': cattree,
        'currentcategory': curcat,
        'global_message' : gm,
        'category_path':get_category_path(curcat),
    }